package jp.com.nobnak.commentviewer.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jp.com.nobnak.commentviewer.common.IAction1;
import jp.com.nobnak.commentviewer.common.IPair;
import android.net.Uri;

public class UriCommandLauncher {
	static public final int NO_MATCH = -1;
	
	
	private List<Pair>mLauncher = new ArrayList<Pair>();
	
	
	public void addCommand(Pattern pattern, IAction1<Matcher> action) {
		mLauncher.add(new Pair(pattern, action));
	}
	
	public boolean launch(Uri uri) {
		for (Pair pair : mLauncher) {
			Matcher matcher = pair.first().matcher(uri.toString());
			if (matcher.find()) {
				try {
					pair.second().call(matcher);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}
				
		}
		return false;
	}
}


class Pair implements IPair<Pattern, IAction1<Matcher>> {
	private final Pattern _first;
	private final IAction1<Matcher> _second;


	public Pair(Pattern first, IAction1<Matcher> second) {
		this._first = first;
		this._second = second;
	}
	
	@Override
	public Pattern first() {
		return _first;
	}

	@Override
	public IAction1<Matcher> second() {
		return _second;
	}
}